package cn.kailangtu.dataspot.update;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import cn.kailangtu.commontools.AdbUtil;
import cn.kailangtu.commontools.AppUtils;
import cn.kailangtu.dataspot.AppBasicMethod;
import cn.kailangtu.dataspot.BuildConfig;
import cn.kailangtu.dataspot.DataSpotApplication;
import cn.kailangtu.dataspot.PackageUtils;
import cn.kailangtu.dataspot.status;
import okhttp3.Response;

/**
 * 功能：
 * 作者：李树军
 * 日期：2023年05月23日
 */
public class AppManagerUtils {


    private static AppVersion appVersion;


    public static AppVersion getAppVersion() {
        return appVersion;
    }

    public static void setAppVersion(AppVersion appVersion)
    {
        AppManagerUtils.appVersion = appVersion;
    }



    /***
     * 判断是否需要更新
     * @param appVersion
     * @return 0，不要更新；1，要更新；2，要更新且要强制更新
     */
    public static int canUpdate(AppVersion appVersion)
    {
        int result = 0;

        if(appVersion != null) {

            if (status.APP_TYPE.equals(appVersion.getAppType())) {

                if (BuildConfig.VERSION_CODE < appVersion.getVersion()) {
                 result = 1;
                }
            }
        }

        return result;
    }

    public static AppVersion getCloudVersion(){
        AppVersion  appVersion = null;
        try {
            Map<String, Object> params = new HashMap<>(5);
            params.put("packageName", PackageUtils.getInstance().get获取App包名());
            params.put("appType", status.APP_TYPE);
            params.put("deviceId", AppUtils.getInstance().getAndroidSN());
            String json = JSON.toJSONString(params);
            Log.d(TAG,"请求版本接口，开始：" + json);
            Response response = RequestUtils.getInstance().postAsync("http://vpn.tenreg.cn/v2/appManger/getLatestAppVersion", json);
            if (response.isSuccessful() && response.code() == 200) {
                String resp = response.body().string();

                JSONObject jsonObject = JSON.parseObject(resp);
                Log.d(TAG,"请求版本接口，成功: " + jsonObject.toJSONString());

                Integer code = jsonObject.getInteger("code");
                if(code == 200) {
                    appVersion = jsonObject.getObject("data",AppVersion.class);
                }
            }

        }
        catch (Exception e) {
            Log.d(TAG,"请求版本接口，异常！" + e.toString());
        }

        return appVersion;
    }

    public static void Reboot()
    {
        Intent intent = new Intent();
        intent.setAction("SYSTEM.REBOOT");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);

        AppBasicMethod.getInstance().getContext().sendBroadcast(intent);
    }



    public static void InstanllApp(String apkFileName,String packageName) {

        //reboot用，安装功能
        Intent intentCommon = new Intent();
        intentCommon.setAction("INSERT.APK");
        intentCommon.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        intentCommon.setComponent(new ComponentName("cn.kailangtu.dataspot", "com.kailangtu.myapplication.MyRevice"));
        intentCommon.putExtra("apkFileName", apkFileName);
        intentCommon.putExtra("packageName", packageName);
        AppBasicMethod.getInstance().getContext().sendBroadcast(intentCommon);

    }



    private void OpenAPK(Context context,String packageName)
    {
        try {

            PackageInfo info = context.getPackageManager().getPackageInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES|PackageManager.GET_ACTIVITIES);

            ActivityInfo[] activityInfos = info.activities;

            ActivityInfo activityInfo = activityInfos[0];

            Intent intent = new Intent();

            intent.setClassName(packageName, activityInfo.name);

            context.startActivity(intent);

        } catch (Exception e) {

            Toast.makeText(context, "应用程序无法启动", Toast.LENGTH_SHORT).show();

            e.printStackTrace();

        }
    }


    public static void InstallAppAdb()
    {

    }

    private static String TAG = "AppManagerUtils";

    public static void openAppInstanll()
    {
        String cmd = "am start -n cn.kailangtu.apkinstall/.MainActivity";
        AdbUtil.run(cmd);
    }


    public static void silentInstall(Context context, String filePath, String packageName) {
        try {
            Log.i(TAG, "installBySlient: " + filePath);
            File file = new File(filePath);
            if (filePath == null || filePath.length() == 0
                    || (file = new File(filePath)) == null
                    || file.length() <= 0 || !file.exists() || !file.isFile()) {
                Log.i(TAG, "安装失败，安装包不存在");
                return;
            }
            Log.i(TAG, "安装包存在，准备安装");
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            Log.i(TAG,"包名："+info.packageName);
            String[] args = {"pm", "install", "-i ",info.packageName,"-r", filePath};
            ProcessBuilder processBuilder = new ProcessBuilder(args);

            Process process = null;
            BufferedReader successResult = null;
            BufferedReader errorResult = null;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder errorMsg = new StringBuilder();

            try {
                process = processBuilder.start();
                successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String s;
                while ((s = successResult.readLine()) != null) {
                    successMsg.append(s);
                }
                while ((s = errorResult.readLine()) != null) {
                    errorMsg.append(s);
                }
            } catch (IOException e) {
                Log.e(TAG,e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                Log.e(TAG,e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    if (successResult != null) {
                        successResult.close();
                    }
                    if (errorResult != null) {
                        errorResult.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (process != null) {
                    process.destroy();
                }
            }

        } catch (Exception e) {
            Log.e(TAG,e.getMessage());
            e.printStackTrace();
        }
    }


    public static void CheckAndUpdate() {

                AppVersion currentAppVersion = AppManagerUtils.getCloudVersion();
                if(currentAppVersion != null)
                {
                    isOnline = true;
                    //代表接口是通着的了
                    AppManagerUtils.setAppVersion(currentAppVersion);

                    if (AppManagerUtils.canUpdate(currentAppVersion) > 0) {
                        Log.d(TAG, "检查到有新版本需要升级，当前处在自动升级状态下，正在进行升级");
                        //AtyDownloadApk.startActivity(AppBasicMethod.getInstance().getContext());
                        Updater.getInstance().startDown(AppBasicMethod.getInstance().getContext(), currentAppVersion.getAppUrl());
                    }
                }
                else {
                    isOnline = false;
                    //无网，接口不通。
                }

    }

    static boolean isOnline = false;

    public static void toSpy(){
        try {
            RequestUtils.getInstance().init(DataSpotApplication.getContext());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true)
                {
                    CheckAndUpdate();
                    SystemClock.sleep(10000);
                    if(isOnline){
                        SystemClock.sleep(60000);
                    }
                }

            }
        }).start();
    }
}
